<?php

namespace App\Services;

class JinShouFuHelper
{
    function fromKey($key): string
    {
        $publicKey = "-----BEGIN PUBLIC KEY-----\n";
        $nextIndex = 0;
        $keyLength = strlen($key);

        do {
            if ($nextIndex + 64 > $keyLength) {
                $publicKey .= substr($key, $nextIndex) . "\n";
            } else {
                $publicKey .= substr($key, $nextIndex, 64) . "\n";
            }
            $nextIndex += 64;
        } while ($nextIndex < $keyLength);

        $publicKey .= "-----END PUBLIC KEY-----";

        return $publicKey;
    }

    function setKey($key): string
    {
        $publicKey = "-----BEGIN PUBLIC KEY-----\n";
        $publicKey .= $key."\n";

        $publicKey .= "-----END PUBLIC KEY-----";
//        var_dump($publicKey);
//        exit();
        return $publicKey;
    }

    public function encrypt($data, $publicKey, $padding = OPENSSL_PKCS1_PADDING) {
        // 解析公钥
        $publicKeyResource = openssl_pkey_get_public($publicKey);
        if (!$publicKeyResource) {
            return false;
        }
        // 执行加密
        $encrypted = '';
        $result = openssl_public_encrypt($data, $encrypted, $publicKeyResource, $padding);

        if ($result) {
            // 加密结果进行base64编码，方便传输
            return base64_encode($encrypted);
        }

        return false;
    }


}
